// pages/todos/todos.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
      /* 文本框的数据模型 */
      input:"",
      todos:[
        {
          id:1,
          name:'Learning HTML',
          completed: true
        },
        {
          id:2,
          name:'Learning CSS',
          completed: false
        },
        {
          id:3,
          name:'Learning JavaScript',
          completed:false
        },
      ],
      leftCount:2,
      allCompleted:false,
  },
  addTodoHandle(){
    // console.log(222);
    // console.log(this.data.input);
    if (!this.data.input)return
   var todos= this.data.todos
   todos.push({
     name:this.data.input,
     completed:false
   })
   this.setData({
     todos,
     input:'',
     leftCount:this.data.leftCount+1
   })
  },
  inputChangeHandle(e){
    // console.log(333);
    // console.log(e.detail);
    this.setData({
      input:e.detail.value
    })
  },
  toggleTodoHandle (e){
    /* 切换当前点中的item的完成状态 */ 
    console.log(e.currentTarget);
    var item = this.data.todos[e.currentTarget.dataset.index]
    console.log(item);
    item.completed=!item.completed
    var leftCount = this.data.leftCount+ (item.completed?-1: +1)
    this.setData({
      todos:this.data.todos,
      leftCount
    })
  },
  removeTodoHandle(e){
    console.log(e.currentTarget);
    var todos =this.data.todos
    /* item 就是splice方法中移除掉的元素 */
    var item=todos.splice(e.currentTarget.dataset.index,1)[0] /* 因为删除的是数组，所以要拿到第一个元素 */
    var leftCount=this.data.leftCount+(item.completed?0:- 1)
    this.setData({
      todos,
      leftCount
    })
  },
  toggleAllHandle(){
    this.data.allCompleted=!this.data.allCompleted
    var todos=this.data.todos
    todos.forEach(item=>{
     item.completed = this.data.allCompleted
    })
    var leftCount =this.data.allCompleted?0:this.data.todos.length
    this.setData({
      todos,
      leftCount
    })
  },
  chearHandle(){
    var todos =this.data.todos.filter(item=>{
      return !item.completed
    })
    this.setData({
      todos
    })
  },







  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})